package written;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 写个JAVA程序开启5个计数线程从0开始计数，当所有线程计数值到1000时输出一个HelloWorld字符串
 *
 * @author TANGYE
 * @date 2021-01-02 10:09
 **/
public class QuestionTwoByCDL implements Runnable, Cloneable {
    private static final int MAX_VALUE = 10000;
    private static AtomicInteger num = new AtomicInteger(0);
    private CountDownLatch cdl;

    public QuestionTwoByCDL(CountDownLatch cdl) {
        this.cdl = cdl;
    }

    @Override
    public QuestionTwoByCDL clone() throws CloneNotSupportedException {
        return (QuestionTwoByCDL) super.clone();
    }

    public synchronized void printHelloWorld(int maxValue, AtomicInteger num) {
        if (num.addAndGet(1) == maxValue) {
            System.out.println("Thread is: " + Thread.currentThread().getName() + ",  num is:" + num.get());
            System.out.println("HelloWorld");
        }
//        try {
//            if (num.get() % 10 == 0) {
//                Thread.currentThread().sleep(20);
//            }
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    }


    public static void main(String[] args) throws InterruptedException {
        CountDownLatch cdl = new CountDownLatch(5);
        QuestionTwoByCDL questionTwoByCDL = new QuestionTwoByCDL(cdl);
        Thread t1 = new Thread(questionTwoByCDL, "Thread1");
        Thread t2 = new Thread(questionTwoByCDL, "Thread2");
        Thread t3 = new Thread(questionTwoByCDL, "Thread3");
        Thread t4 = new Thread(questionTwoByCDL, "Thread4");
        Thread t5 = new Thread(questionTwoByCDL, "Thread5");

        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        //cdl.await();
        Thread.currentThread().sleep(50000);
        System.out.println(Thread.currentThread().getName() + ": End......");
    }

    @Override
    public void run() {
        while (num.get() < MAX_VALUE) {
            printHelloWorld(MAX_VALUE, num);
        }
        cdl.countDown();
    }
}
